package com.creditease.shield.flow.boot;

import com.creditease.shield.flow.base.MyBatisDao;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by apple on 16/6/20.
 */
@Configuration
@MapperScan(basePackages = "com.creditease.shield.flow.dao")
public class MyBatisDatabaseConfig {

    /**
     * 将mybatis的sqlSessionFactory交给spring管理
     */    
    @Bean
    public SqlSessionFactory sessionFactory(DataSource shardingDataSource) throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(shardingDataSource);
        sessionFactory.setTypeAliasesPackage("com.creditease.shield.flow.pojo");
        Properties properties=new Properties();
        properties.setProperty("cacheEnabled","true");
        properties.setProperty("lazyLoadingEnabled","true");
        properties.setProperty("aggressiveLazyLoading","true");
        properties.setProperty("multipleResultSetsEnabled","true");
        properties.setProperty("useColumnLabel","true");
        properties.setProperty("useGeneratedKeys","true");
        properties.setProperty("autoMappingBehavior","");

        properties.setProperty("defaultExecutorType","SIMPLE");
        properties.setProperty("mapUnderscoreToCamelCase","true");
        properties.setProperty("localCacheScope","SESSION");
        properties.setProperty("jdbcTypeForNull","NULL");
        sessionFactory.setConfigurationProperties(properties);
        
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
        return sessionFactory.getObject();

    }
    
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {

        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        scannerConfigurer.setBasePackage("com.creditease.shield.flow.dao");
        scannerConfigurer.setAnnotationClass(MyBatisDao.class);

        return scannerConfigurer;
    }
    
}
